<template>
  <div class="main">
    <section>
      <search-form :listQuery="listQuery" :queryConfig="queryConfig" :labelWidth="100" :search="search"/>
      <el-button type="primary" style="margin-bottom:20px" @click="addOrEditActivaty('', 0)">新建</el-button>
      <el-table v-loading="loading" :data="list" element-loading-text="给我一点时间" border fit highlight-current-row>
        <el-table-column align="center" type="index" label="序号" width="60">
        </el-table-column>
        <el-table-column align="center" prop="name" label="活动名称">
        </el-table-column>
        <el-table-column align="center" label="活动时间">
          <template slot-scope="scope">
            {{formatDate(scope.row.startTime, 'YYYY-MM-DD HH:mm:ss')}}至{{formatDate(scope.row.endTime, 'YYYY-MM-DD HH:mm:ss')}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="statusName" label="活动状态"></el-table-column>
        <el-table-column align="center" label="操作" width="210">
          <template slot-scope="scope">
            <el-button type="text" plain @click="addOrEditActivaty(scope.row, 1)">编辑</el-button>
            <el-button type="text" plain @click="endActivaty(scope.row.activityFullGiveId)">结束</el-button>
            <el-button type="text" plain @click="addOrEditActivaty(scope.row, 2)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum"
        :page-sizes="[10, 20, 50, 100]" :page-size="listQuery.pageSize" background layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"></el-pagination>
    </section>
    <el-dialog :title="type===0?'新增':type===1?'编辑':'查看'" :visible.sync="dialogActivaty" width="40%" :close-on-click-modal="false">
      <el-form :model="formData" :rules="formRules" ref="formData" label-width="120px">
        <el-form-item label="活动名称:" prop="name">
          <el-input v-model="formData.name" placeholder="活动名称" :disabled="type===2"></el-input>
        </el-form-item>
        <el-form-item label="活动时间:" prop="timeRange">
          <el-date-picker
            :disabled="type===2"
            v-model="formData.timeRange"
            type="datetimerange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动条件:" prop="money">
          <el-row>
            <el-col :span="4">商品金额满</el-col>
            <el-col :span="16"><el-input v-model="formData.money" :disabled="type===2"></el-input></el-col>
            <el-col :span="4">&nbsp;&nbsp;&nbsp;元</el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="活动优惠:" prop="couponActivityNameList">
          <el-input v-model="formData.couponActivityNameList" placeholder="活动优惠" @focus="jumpChoose" :disabled="type===2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogActivaty = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="saveLoading" v-show="this.type!==2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import searchForm from '@/components/searchForm/index'
export default {
  name: 'b-fullcoupon',
  components: {
    searchForm
  },
  data() {
    return {
      formData: {
        name: '',
        timeRange: [],
        startTime: '',
        endTime: '',
        money: null,
        couponActivityIdList: [],
        couponActivityNameList: ''
      },
      formRules: {
        name: [{required: true, message: '不能为空', trigger: 'blur'}],
        timeRange: [{required: true, message: '不能为空', trigger: 'change'}],
        money: [
          {required: true, message: '不能为空', trigger: 'blur'},
          { pattern: /^\d+(.\d+)?$/, message: '请输入数字', trigger: 'blur'}
        ],
        couponActivityNameList: [{required: true, message: '不能为空', trigger: 'change'}],
      },
      saveLoading: false,
      listQuery: {
        pageNum: 0,
        pageSize: 10,
        name: ''
      },
      queryConfig: [
        {
          prop: 'name',
          type: 'input',
          label: '活动名称'
        }
      ],
      dialogActivaty: false,
      loading: true,
      listTotal: 0,
      list: [],
      couponActivityIdList: [],
      type: 0 // 0 新建 1 编辑 2查看
    }
  },
  created () {
    if (this.$store.getters.cachedViews.length === 0) this.getList()
  },
  activated () {
    this.getList()
  },
  methods: {
    jumpChoose () {
      let array = []
      let checkData = this.couponActivityIdList.filter(item => item.rewardType === 4).map(i => {
        return {
          couponActivityId: i.couponActivityId,
          name: i.name
        }
      })
      this.couponChoose({ validFlag: true }, checkData).then(val => {
        this.couponActivityIdList = this.couponActivityIdList.filter(item => item.rewardType !== 4)
        console.log('this.couponActivityIdList', this.couponActivityIdList)
        val.map(i => {
          this.couponActivityIdList.push({
            couponActivityId: i.couponActivityId,
            name: i.name,
            rewardType: 4
          })
          this.formData.couponActivityIdList.push(i.couponActivityId)
          array.push(i.name)
        })
        console.log('array', array)
        this.$set(this.formData, 'couponActivityNameList', array.join(','))
      })
    },
    async getList() {
      this.loading = true
      this.request({
        url: '/bihs/activity/full-give/list',
        method: 'post',
        data: this.listQuery
      }).then(({data}) => {
        this.loading = false
        this.list = data.list
        this.listTotal = data.total
      }).catch(err => {
        console.log(err)
        this.list = []
        this.listTotal = 0
        this.loading = false
      })
    },
    endActivaty(id) {
      this.$confirm('是否结束该活动?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request({
          url: '/bihs/activity/full-give/delete',
          method: 'get',
          params: {
            activityFullGiveId : id 
          }
        }).then(() => {
          this.$message.success('结束成功')
          this.getList()
        }).catch(err => {
          console.log(err)
        })
      }).catch(error => {
        console.log( error)
      })
    },
    addOrEditActivaty(row, type) {
      this.couponActivityIdList = []
      this.dialogActivaty = true
      this.type = type
      if (row) this.activityFullGiveId = row.activityFullGiveId
      if (type === 0) {
        this.formData = {
          name: '',
          timeRange: [],
          startTime: '',
          endTime: '',
          money: null,
          couponActivityIdList: [],
          couponActivityNameList: ''
        }
        this.$nextTick(() => {
          this.$refs.formData.clearValidate()
        })
      } else {
        this.request({
          url: '/bihs/activity/full-give/info',
          method: 'get',
          params: {
            activityFullGiveId: row.activityFullGiveId
          }
        }).then((res) => {
          this.formData = Object.assign({}, res.data)
          this.formData.timeRange = [this.formData.startTime, this.formData.endTime]
          let array = []
          this.formData.couponActivityIdList = []
          this.formData.couponActivityModelList.forEach((item) => {
            array.push(item.couponName)
            this.couponActivityIdList.push({
              couponActivityId: item.couponActivityId,
              name: item.couponName,
              rewardType: 4
            })
          })
          this.$set(this.formData, 'couponActivityNameList', array.join(','))
        }).catch(err => {
          console.error(err)
        })
        
      }
    },
    async submit() {
      this.$refs.formData.validate(valid => {
        if (!valid) {
          return false
        }
        let path = this.type === 0 ? '/bihs/activity/full-give/add' : '/bihs/activity/full-give/edit'
        this.formData.startTime = this.formData.timeRange[0]
        this.formData.endTime = this.formData.timeRange[1]
        if (this.type === 1) this.formData.activityFullGiveId = this.activityFullGiveId
        this.saveLoading = true
        this.request({
          url: path,
          method: 'post',
          data: this.formData
        }).then(() => {
          this.$message.success('保存成功')
          this.saveLoading = false
          this.dialogActivaty = false
          this.getList()
        }).catch(err => {
          console.error(err)
          this.saveLoading = false
        })
      })
    },
    search() {
      this.getList()
    },
    //切换每页条数
    handleSizeChange(value) {
      this.listQuery.pageSize = value
      this.getList()
    },
    // 切换分页
    handleCurrentChange(page) {
      this.listQuery.pageNum = page
      this.getList()
    }
  }
}
</script>

 